#include <ros/ros.h>
#include <tf/transform_listener.h>
#include <geometry_msgs/Twist.h>
#include <turtlesim/Spawn.h>
#include <sstream>
using namespace std;

int main(int argc, char** argv)
{
    // 初始化节点
    ros::init(argc, argv, "my_tf_listener");
    ros::NodeHandle node;
    
    string turtle_name = "";
    string traing_frame = "";
    float triangle_scale = 2.0;
    string turtle_pose = "";
    

    ros::param::get("~turtle_name",turtle_name);
    ros::param::get("~traing_frame",traing_frame);
    ros::param::get("triangle_scale",triangle_scale);
    ros::param::get("~turtle_pose",turtle_pose);
    ROS_INFO("turtle_pose:%s",turtle_pose.c_str());
    //调用服务生成小乌龟
    ros::service::waitForService("spawn");
    ros::ServiceClient add_turtle = node.serviceClient<turtlesim::Spawn>("spawn");
    turtlesim::Spawn srv;
    srv.request.x = 1;
    srv.request.y = 1;
    srv.request.theta = 0;
    srv.request.name = turtle_name.c_str();
    add_turtle.call(srv);
    // 定义一个turtle2的速度控制发布器
    ros::Publisher turtle_vel = node.advertise<geometry_msgs::Twist>(turtle_name+"/cmd_vel", 10);
    // tf监听器
    tf::TransformListener listener;
    ros::Rate rate(10.0);
    while (node.ok())
    {
        tf::StampedTransform transform;
        try
        {
            // 查找turtle2与turtle1的坐标变换 carrot1
            listener.waitForTransform("/"+turtle_name, "/"+traing_frame, ros::Time(0), ros::Duration(3.0));
            //获取两个坐标系之间的转换关系，包括旋转平移。主要步骤有
            listener.lookupTransform("/"+turtle_name, "/"+traing_frame, ros::Time(0), transform);
        }
        catch (tf::TransformException &ex) 
        {
            ROS_ERROR("%s",ex.what());
            ros::Duration(1.0).sleep();
            continue;
        }
 
        // 根据小乌龟跟要跟踪的坐标系之间的坐标变换，计算小乌龟需要运动的线速度和角速度
        // 并发布速度控制指令，使小乌龟向目标移动
        geometry_msgs::Twist vel_msg;
        if( fabs(sqrt(pow(transform.getOrigin().x(), 2) + pow(transform.getOrigin().y(), 2)))>0.01)
        {
            vel_msg.angular.z = 4.0 * atan2(transform.getOrigin().y(),transform.getOrigin().x());
            vel_msg.linear.x = 3.0 * sqrt(pow(transform.getOrigin().x(), 2) + pow(transform.getOrigin().y(), 2));
        }
        else
        {
             vel_msg.angular.z = 0;
             vel_msg.linear.x = 0;
            }
        turtle_vel.publish(vel_msg);
 
        rate.sleep();
    }
    return 0;
};